<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }
        
        .box {
            width: 200px;
            height: 200px;
            background: red;
            position: absolute;
        }
        
        .box h4 {
            background: #ccc;
            text-align: center;
        }
    </style>
</head>

<body>
    <div class="box" id="box1">box1</div>
    <div class="box" id="box2">
        <h4>title</h4>
    </div>
    <script>
        class Drag {
            constructor(selector, title) {
                this.box = document.querySelector(selector)
                this.title = title ? this.box.querySelector(title) : this.box;
                this.bindEvents()
            }
            bindEvents() {
                const _this = this;
                this.title.onmousedown = function(e) {
                    let disX = e.offsetX,
                        disY = e.offsetY;
                    document.onmousemove = function(e) {
                        let left = e.clientX - disX,
                            top = e.clientY - disY;
                        _this.move(left, top)
                    }
                    document.onmouseup = function() {
                        document.onmousemove = null;
                    }
                    e.preventDefault()
                }
            }
            move(left, top) {
                var ht = document.body.clientHeight || document.documentElement.clientHeight;
                if (left < 0) left = 0;
                if (top < 0) top = 0;
                if (left > document.body.clientWidth - this.box.offsetWidth) left = document.body.clientWidth - this.box.offsetWidth;
                console.log(ht)
                if (top > ht - this.box.offsetHeight) top = ht - this.box.offsetHeight;
                this.box.style.left = left + 'px';
                this.box.style.top = top + 'px';
            }
        }
        new Drag('#box1')
        new Drag('#box2', 'h4')
    </script>
</body>

</html>